package reflect;

import java.lang.reflect.Field;

/**
 * 访问私有属性
 */
public class ReflectDemo9 {
    public static void main(String[] args) throws Exception {
        Person person = new Person("张三", 20);
        System.out.println(person);
        //获取person对象所属类的类对象
        Class cls = person.getClass();
        //获取age属性
        Field field = cls.getDeclaredField("age");
        field.setAccessible(true);
        field.set(person, 30);//person.age=30;
        int age = (Integer)field.get(person);//int age = person.age;
        System.out.println("年龄:"+age);
        field.setAccessible(false);
        System.out.println(person);
    }
}
